package com.weishui.talking.socket;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;

import com.weishui.talking.app.TalkingWindow;
import com.weishui.talking.util.Constant;

public class ClientSocket {
	static Logger logger = Logger.getLogger(ClientSocket.class);
	
	private static Socket socket = null;
	private static PrintWriter pw = null;
	
	public static boolean sendMessage(String serverIp,String contentMessage){
		try {
			socket = new Socket(serverIp,Constant.serverPort);
			pw = new PrintWriter(socket.getOutputStream(),true);
			pw.println(InetAddress.getLocalHost().getHostAddress() + ":" +contentMessage);
			TalkingWindow.addLog(InetAddress.getLocalHost().getHostAddress() + ":" + contentMessage.toString());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			logger.error("UnknownHost",e);
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error("IOException",e);
			return false;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("Exception",e);
			return false;
		}finally{
			try {
				if(pw != null){
					pw.close();
				}
				if(socket != null){
					socket.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error("close resource IOException",e);
				return false;
			}catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error("close resource Exception",e);
				return false;
			}
		}
		return true;
	}
}
